Displaying Connections (Contacts)
Now that you've initialized the One37ID agent and handled email verification, it’s time to display all the user’s connections (or contacts) in the app. A connection in this context is a secure relationship established between the user and another party, such as a business.
In this step, we’ll create a ContactScreen that retrieves and displays a list of these connections.
Creating the Contact Screen UI
To begin, we’ll leverage the One37ID SDK's contactManager
to fetch the list of contacts associated with the user. The function fetchContacts
below fetches the list of connections using pagination.
We’ll create a new screen called ContactScreen
where the user can view a list of their contacts and create new ones. The code below provides a simple example:
import React, { useEffect, useState } from "react";
import {
View,
Text,
FlatList,
TouchableOpacity,
StyleSheet,
ActivityIndicator,
Alert,
Image,
} from "react-native";
import Ionicons from "react-native-vector-icons/Ionicons";
import { CustomAddContactModal } from "../../components/contact/CustomAddContactModal"; // Ensure you have this modal
import { useNavigation } from "@react-navigation/native";
import { Contact } from "@one37id/mobile-js-sdk"; // Import the Contact type from SDK
import { initializeAgent } from "../../one37Agent";
const ContactScreen = () => {
const [contacts, setContacts] = useState([]); // State to hold contact data
const [loading, setLoading] = useState(true); // Loading state
const [modalVisible, setModalVisible] = useState(false); // Add contact modal state
const navigation = useNavigation(); // Access the navigation object
// Function to fetch contacts
const fetchContacts = async () => {
const agent = await initializeAgent(); // Initialize the agent
if (!agent) {
console.error("Agent not initialized");
return [];
}
try {
const connections = await agent.contactManager.getList({
currentPage: 1,
rowsPerPage: 1000,
});
console.log("Connections:", connections.result);
return connections.result; // Return the list of contacts
} catch (error) {
console.error("Error fetching contacts:", error);
return [];
}
};
// Fetch contacts on mount
useEffect(() => {
const loadContacts = async () => {
setLoading(true);
const connections = await fetchContacts(); // Fetch the contacts
setContacts(connections || []); // Update state with contacts
setLoading(false); // Stop loading once done
};
loadContacts();
}, []);
// Handle adding a new contact
const handleAddContact = () => {
setModalVisible(true); // Open the modal to add a contact
};
// Handle when a contact is added and refresh the contact list
const handleContactAdded = async () => {
try {
console.log("Fetching updated contacts");
const updatedContacts = await fetchContacts(); // Fetch updated contacts
setContacts(updatedContacts || []); // Update state with new contacts
} catch (error) {
console.error("Error fetching updated contacts:", error);
}
};
// Handle deleting a contact with confirmation
const deleteContact = async (contact: Contact) => {
const agent = await initializeAgent();
if (!agent) {
console.error("Agent not initialized");
return;
}
try {
const result = await agent.contactManager.delete(contact); // Call SDK to delete contact
if (result.isSuccessful) {
setContacts(contacts.filter((c) => c.id !== contact.id)); // Remove contact from UI if successful
} else {
Alert.alert("Error", "Failed to delete contact.");
}
} catch (error) {
console.error("Error deleting contact:", error);
Alert.alert("Error", "An error occurred while deleting the contact.");
}
};
// Handle long press for deleting a contact
const onLongPress = (contact: Contact) => {
Alert.alert(
"Delete Contact",
`Are you sure you want to delete ${contact.displayName}?`,
[
{ text: "Cancel", style: "cancel" },
{
text: "Yes",
onPress: () => deleteContact(contact),
},
],
{ cancelable: true }
);
};
// Handle title press to navigate to the contact's detail screen
const onTitlePress = (contact: Contact) => {
navigation.navigate("BusinessContactCredentialsScreen", { contact });
};
// If loading, show a spinner
if (loading) {
return <ActivityIndicator size="large" color="#0000ff" />;
}
return (
<View style={styles.container}>
{/* Header with add contact button */}
<View style={styles.header}>
<Text style={styles.headerText}>Contacts</Text>
<TouchableOpacity onPress={handleAddContact}>
<Ionicons name="add-circle-outline" size={30} color="black" />
</TouchableOpacity>
</View>
{/* FlatList to display the contacts */}
<FlatList
data={contacts}
keyExtractor={(item) => item.id}
renderItem={({ item }) => (
<View style={styles.contactItem}>
<TouchableOpacity
onPress={() => onTitlePress(item)} // Navigate to detail screen
onLongPress={() => onLongPress(item)} // Delete on long press
style={styles.contactContent}
>
{/* Display the logoUrl if available */}
{item.logoUrl ? (
<Image source={{ uri: item.logoUrl }} style={styles.logo} />
) : (
<Ionicons name="person-circle-outline" size={40} color="gray" />
)}
<Text style={styles.contactName}>{item.displayName}</Text>
</TouchableOpacity>
</View>
)}
/>
{/* Add Contact Modal */}
<CustomAddContactModal
modalVisible={modalVisible}
setModalVisible={setModalVisible}
onContactAdded={handleContactAdded} // Update contact list when a contact is added
/>
</View>
);
};
// Styles for the component
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
header: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
marginBottom: 20,
},
headerText: {
fontSize: 20,
fontWeight: "bold",
},
contactItem: {
padding: 15,
borderBottomWidth: 1,
borderBottomColor: "#ccc",
},
contactContent: {
flexDirection: "row",
alignItems: "center",
},
contactName: {
fontSize: 18,
marginLeft: 10,
},
logo: {
width: 40,
height: 40,
borderRadius: 20,
},
});
export default ContactScreen;
What’s Happening?
-
Fetching Connections: The
fetchContacts()
function retrieves the user's contacts (connections) from the One37ID platform. It returns an array of connection objects. -
Displaying Contacts: The contacts are displayed using React Native's
FlatList
. Each contact is represented as a simple text element showing thedisplayName
property and when clicking on the title it takes him to the next page having the contact object as params. -
Adding New Contacts: A button with an “Add” icon is displayed in the header, which could trigger a modal (like
AddContactModal
) to add new contacts.